
package com.v1.video.activity;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.SectionIndexer;
import android.widget.TextView;
import android.widget.Toast;

import com.iss.view.common.ToastAlone;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.domain.CityChoiceinfo;
import com.v1.video.util.CityChoiceDBUtil;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;
import com.v1.video.view.LetterListView;
import com.v1.video.view.LetterListView.OnTouchingLetterChangedListener;

public class CityChoiceActivity extends BaseActivity {
    private LetterListView letterListView;
    private ListView content;
    private CityListAdapter contentAdapter;
    private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置
    private String[] sections;// 存放存在的汉语拼音首字母
    private Handler handler;
    private TextView overlay;
    private OverlayThread overlayThread;
    private TextView choiceAddress,mTvRight;
    private CityChoiceinfo choiceinfo = new CityChoiceinfo();
    
    private TextView txtTitle = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_city_choice);
    }

    @Override
    protected void initView() {
        content = (ListView) findViewById(R.id.citychoice_content);
        letterListView = (LetterListView) findViewById(R.id.citychoice_letter);
        choiceAddress = (TextView) findViewById(R.id.tv_choice_address);
        
        txtTitle = (TextView)findViewById(R.id.tv_title);
        mTvRight=(TextView) findViewById(R.id.tv_right);
    }

    @Override
    protected void initData() {
        txtTitle.setText(R.string.activity_shooting_site_side_citychoice);
//        mTvRight.setVisibility(View.VISIBLE);
        mTvRight.setText("下一 步");
        String address = getIntent().getStringExtra("currentPosition");
        if (!TextUtils.isEmpty(address)) {
            choiceAddress.setText(address);
            if(!Constant.NO_GET_POSITION.equals(address)){
                String[] split = address.split(" ");
                if(split != null && split.length ==2){
                    choiceinfo.setProname(split[0]);
                    choiceinfo.setCityname(split[1]);
                }
            }
        }

        copyFile("city.db");
        
    }

    @Override
    protected void setListener() {

        letterListView.setOnTouchingLetterChangedListener(new LetterListViewListener());

        content.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityListAdapter adapter = (CityListAdapter) parent.getAdapter();
                CityChoiceinfo info = (CityChoiceinfo) adapter.getItem(position);
//                choiceAddress.setText(info.getProname() +" "+ info.getCityname());
//                choiceinfo = info;
                Intent intent = new Intent();
                intent.putExtra("proname", info.getProname());
                intent.putExtra("cityname", info.getCityname());
                setResult(0, intent);
                CityChoiceActivity.this.finish();
            }
        });

        findViewById(R.id.lay_result).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                finish();
            }
        });
        mTvRight.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                if(choiceinfo != null){
                	
                    Intent intent = new Intent();
                    intent.putExtra("proname", choiceinfo.getProname());
                    intent.putExtra("cityname", choiceinfo.getCityname());
                    setResult(0, intent);
                    CityChoiceActivity.this.finish();
                }else{
                    ToastAlone.showToast(CityChoiceActivity.this, "未选择任何地区", 0);
                    
                }
            }
        });

    }

    private class loadCitysAsync extends AsyncTask<Void, Void, Void> {

        private List<CityChoiceinfo> citys;

        private ProgressDialog pd;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pd = Utils.getProgressDialog(CityChoiceActivity.this, this);
            pd.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            try {
                CityChoiceDBUtil dao = new CityChoiceDBUtil(CityChoiceActivity.this);
                citys = dao.getCitys();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            if (pd != null && pd.isShowing()) {
                pd.cancel();
            }
            if (citys != null && !citys.isEmpty()) {
                contentAdapter = new CityListAdapter(CityChoiceActivity.this, citys);
                content.setAdapter(contentAdapter);
                sections = (String[]) contentAdapter.getSections();
                alphaIndexer = contentAdapter.getAlphaIndexer();

            } else {
                Toast.makeText(CityChoiceActivity.this, "初始化城市列表数据失败", Toast.LENGTH_SHORT).show();
            }
        }

    }

    // 设置overlay不可见
    private class OverlayThread implements Runnable {

        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }
    }

    private class LetterListViewListener implements OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                content.setSelection(position);
                overlay.setText(sections[position]);
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟一秒半后执行，让overlay为不可见
                handler.postDelayed(overlayThread, 1500);
            }
        }

    }

    // 初始化汉语拼音首字母弹出提示框
    private void initOverlay() {
        handler = new Handler();
        overlayThread = new OverlayThread();

        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.toast_city_choice, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,
                LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }

    private class CityListAdapter extends BaseAdapter implements SectionIndexer {
        private LayoutInflater inflater;

        private List<CityChoiceinfo> list;

        private HashMap<String, Integer> alphaIndexer;// 保存每个索引在list中的位置【#-0，A-4，B-10】

        private String[] sections; // 每个分组的索引表【A,B,C,F...】

        public CityListAdapter(Context context, List<CityChoiceinfo> list) {
            this.inflater = LayoutInflater.from(context);
            this.list = list; // 该list是已经排序过的集合，有些项目中的数据必须要自己进行排序。
            this.alphaIndexer = new HashMap<String, Integer>();
            sections = new String[list.size()];
            for (int i = 0; i < list.size(); i++) {
                String nameIndex = list.get(i).getCharindex();
                sections[i] = nameIndex;
                if (!alphaIndexer.containsKey(nameIndex)) {// 只记录在list中首次出现的位置
                    alphaIndexer.put(nameIndex, i);
                }
            }

        }

        public HashMap<String, Integer> getAlphaIndexer() {
            return alphaIndexer;
        }

        @Override
        public int getCount() {
            if (list != null) {
                return list.size();
            } else {
                return 0;
            }
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.item_city_choice, null);
                holder = new ViewHolder();
                // holder.alpha = (TextView)convertView.findViewById(R.id.alpha);
                holder.name = (TextView) convertView.findViewById(R.id.name);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            CityChoiceinfo cityinfo = list.get(position);
            String name = cityinfo.getProname() + "  " + cityinfo.getCityname();
            holder.name.setText(name);

            /**
             * 判断显示"热"、A-Z的TextView隐藏与可见
             */
            // 当前联系人的sortKey
            // String currentStr = list.get(position).getCharindex();
            // 上一个联系人的sortKey
            // String previewStr = (position - 1) >= 0 ? list.get(position -
            // 1).getCharindex() : " ";
            // if (!previewStr.equals(currentStr)) {
            // holder.alpha.setVisibility(View.VISIBLE);
            // holder.alpha.setText(currentStr);
            // } else {
            // holder.alpha.setVisibility(View.GONE);
            // }

            return convertView;
        }

        /**
         * 此方法根据联系人的首字母返回在list中的位置
         */
        @Override
        public int getPositionForSection(int section) {
            String later = sections[section];
            return alphaIndexer.get(later);

        }

        @Override
        public int getSectionForPosition(int position) {

            String key = list.get(position).getCharindex();
            for (int i = 0; i < sections.length; i++) {
                if (sections[i].equals(key)) {
                    return i;
                }
            }
            return 0;
        }

        @Override
        public Object[] getSections() {
            return sections;
        }

        private final class ViewHolder {
            TextView alpha;
            TextView name;
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        WindowManager windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        windowManager.removeView(overlay);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    
    //城市数据库
    private static final int REQUEST_CODE = 0;
    
    protected static final int COPY_DATABASE_ERROR = 11;
    protected static final int COPY_DATABASE_SUCCESS = 12;
    
    private ProgressDialog progDialog;
    
    private Handler cityHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
            
            case COPY_DATABASE_SUCCESS :
//                Toast.makeText(getActivity(), "数据库初始化成功", Toast.LENGTH_SHORT).show();
//                startActivityForResult(new Intent(CityChoiceActivity.this, CityChoiceActivity.class).putExtra("currentPosition", currentPosition),REQUEST_CODE);
            	if(progDialog != null && progDialog.isShowing()){
            		progDialog.dismiss();
            		progDialog = null;
            	}
            	new loadCitysAsync().execute();
                initOverlay();
                break;
            case COPY_DATABASE_ERROR :
            	if(progDialog != null && progDialog.isShowing()){
            		progDialog.dismiss();
            		progDialog = null;
            	}
                Toast.makeText(CityChoiceActivity.this, "城市信息初始化失败", Toast.LENGTH_SHORT).show();
                break;
            
            }
        }
    };
    
    private void copyFile(final String filename) {
        final File file = new File(CityChoiceActivity.this.getFilesDir(),filename);
        if(file.exists()&& file.length()>0){
            //已经有了
            Logger.i("TAG", "数据库文件已经存在，不用拷贝");
            Message message = Message.obtain();
            message.what = COPY_DATABASE_SUCCESS;
            cityHandler.sendMessage(message);
        }else{
            //还没有
        	
        	progDialog = ProgressDialog.show(this, null,"正在读取数据", true, false);
        	
            new Thread(){
                public void run() {
                    File destfile = copyFile(CityChoiceActivity.this, filename, file.getAbsolutePath());
                    Message message = Message.obtain();
                    if(destfile!= null){
                        //拷贝数据库成功
                        message.what = COPY_DATABASE_SUCCESS;
                    }else{
                        //拷贝失败
                        message.what = COPY_DATABASE_ERROR;
                    }
                    cityHandler.sendMessage(message);
                     
                };
            }.start();
        }
    }
    
    public static File copyFile(Context context,String fileName,String dest){
        try {
            InputStream is = context.getAssets().open(fileName);//打开assets目录下的文件
            Logger.i(TAG, "dest=="+dest);
            File file = new File(dest);
            FileOutputStream fos =new FileOutputStream(file);
            byte[] b = new byte[1024];
            int len = -1;
            while((len = is.read(b))!= -1){
                fos.write(b, 0, len);
                
            }
            fos.close();
            is.close();
            return file;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        
    }
}
